package com.tianji.config;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class EsClientConfig {
    private static final Logger log = LoggerFactory.getLogger(EsClientConfig.class);

    //创建连接es客户端
    public static RestHighLevelClient client(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")
                        // new HttpHost("localhost", 9201, "http") 多个客户端的时候使用
                )
        );
        return client;
    }

    /**
     * @description ：创建索引库
     * @author hvg
     * @param[1] client es客户端
     * @param[2] indexName 索引库名称
     * @throws
     * @time 2024/8/25 下午6:02
     */
    public static void createIndex(RestHighLevelClient client, String indexName) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        //es创建索引库的sql以及指定json格式
        request.source("user", XContentType.JSON);
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        if(!response.isAcknowledged()){
            log.debug("创建索引库失败");
        }
    }

    public static boolean existIndex(RestHighLevelClient client, String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest(indexName);
        return client.indices().exists(request, RequestOptions.DEFAULT);
    }

    public static void deleteIndex(RestHighLevelClient client, String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        client.indices().delete(request, RequestOptions.DEFAULT);
    }
}
